package com.cnunicom.modules.addressbook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cnunicom.common.utils.PageUtils;
import com.cnunicom.common.utils.Query;
import com.cnunicom.modules.addressbook.dao.AddressBookDao;
import com.cnunicom.modules.addressbook.entity.AddressBookEntity;
import com.cnunicom.modules.addressbook.entity.ChinaEntity;
import com.cnunicom.modules.addressbook.service.AddressBookService;
import com.cnunicom.modules.addressbook.service.ChinaService;
import com.cnunicom.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("addressBookService")
public class AddressBookServiceImpl extends ServiceImpl<AddressBookDao, AddressBookEntity> implements AddressBookService {

    @Autowired
    private ChinaService chinaService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        AddressBookEntity entity = getAddressBookEntity(params);

        IPage<AddressBookEntity> page = this.page(
                new Query<AddressBookEntity>().getPage(params),
                new QueryWrapper<AddressBookEntity>().setEntity(entity)

        );
        page.setRecords(regionProcess(page.getRecords()));

        return new PageUtils(page);
    }

    /**
     * 区域id查询,匹配区域的名称返回
     *
     * @param addressBookList
     * @return
     */
    private List<AddressBookEntity> regionProcess(List<AddressBookEntity> addressBookList) {
        ArrayList<ChinaEntity> chinaList = (ArrayList) chinaService.list();


        //通讯录集合匹配出regionId相同的对象
        addressBookList.forEach(addressBook -> {
            String[] split = addressBook.getRegionId().split(",");
            ArrayList<String> regionName = new ArrayList<>();
            for (String regionId : split) {
                chinaList.forEach(china -> {
                    if (regionId.equals(china.getId().toString())) {
                        regionName.add(china.getName());
                    }
                });
            }
            addressBook.setRegionId(StringUtils.join(regionName.toArray(), "/"));
        });
        return addressBookList;
    }

    /**
     * page查询,参数处理
     * @param params
     * @return
     */
    private AddressBookEntity getAddressBookEntity(Map<String, Object> params){
        AddressBookEntity entity = new AddressBookEntity();

        String regionId = (String) params.get("regionId");

        SysUserEntity user = (SysUserEntity)params.get("user");

        if (StringUtils.isNotBlank(regionId)) {
            entity.setRegionId(regionId);
        }

        return entity;
    }

}
